<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialog" direction="rtl" ref="drawer" width="40%"
      :close-on-click-modal="false" top="8vh">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="140px">
        <br />
        <el-form-item label="优惠券名称" prop="couponTemplateName">
          <el-input v-model="formData.couponTemplateName" placeholder="请输入优惠券名称" clearable :style="{width: '90%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="formData.type" size="medium"  @change="typeChange">
            <el-radio v-for="(item, index) in typeOptions" :key="index" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="适用范围" prop="useScope">
          <el-radio-group v-model="formData.useScope" size="medium"  @change="useChange">
            <el-radio v-for="(item, index) in useOptions" :key="index" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择商品" porp="useGoodsId" v-show="formData.useScope==1">
          <el-select clearable filterable v-model="formData.useGoodsId" :style="{width: '90%'}">
            <el-option v-for="(item,index) in useGoodsList" :key="item.goodsId" :label="item.goodsName" :value="item.goodsId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最低消费" prop="minPrice" v-show="formData.type==0">
          <el-input-number v-model="formData.minPrice" placeholder="优惠券最低消费" :step='1' :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="优惠金额" prop="couponPrice" v-show="formData.type==0">
          <el-input-number v-model="formData.couponPrice" placeholder="优惠金额" :step='1' :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="折扣" prop="discount" v-show="formData.type==1">
          <el-input-number v-model="formData.discount" placeholder="折扣" :step='0.1' :min="0.1" :max="1"></el-input-number>
        </el-form-item>
        <el-form-item label="有效期类型" prop="validType">
          <el-radio-group v-model="formData.validType" size="medium" @change="validTypeChange">
            <el-radio v-for="(item, index) in validTypeOptions" :key="index" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用有效期限天数" prop="validDay" v-show="formData.validType==0">
          <el-input-number v-model="formData.validDay" placeholder="使用有效期限天数" :step='1' :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="使用有效期限范围" v-show="formData.validType==1" prop="isValidDate">
          <el-date-picker type="daterange" @change="selectValidDate" v-model="isValidDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            :style="{width: '500px'}" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取时间" prop="isReceiveDate">
          <el-date-picker type="daterange" @change="selectReceiveDate" v-model="isReceiveDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            :style="{width: '500px'}" start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否限量" prop="isLimited">
          <el-radio-group v-model="formData.isLimited" size="medium" @change="isLimitedChange">
            <el-radio v-for="(item, index) in isLimitedOptions" :key="index" :label="item.value"
              :disabled="item.disabled">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布数量" prop="total" v-show="formData.isLimited==1">
          <el-input-number v-model="formData.total" placeholder="发布数量" :step='1' :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="formData.state" size="medium">
            <el-radio v-for="(item, index) in stateOptions" :key="index" :label="item.value"
              :disabled="item.disabled">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="text-align: center;">
          <el-button type="primary" @click="submitForm" :loading="loading">{{ loading ? '提交中 ...' : '提 交' }}
          </el-button>
          <el-button @click="dialog = false">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

  import {
    addCoupon,updateCoupon,
    infoCoupon,getUseGoodsList
  } from '@/api/mall.product.js'

  export default {
    components: {},
    props: [],
    data() {
      return {
        dialog: false,
        loading: false,
        formData: {
          couponTemplateName: undefined,          // 优惠券名称
          type: 0,                        // 优惠券类型
          minPrice: 0,                    // 优惠券最低消费
          couponPrice: 0,                 // 优惠金额
          discount: undefined,            // 折扣
          validType: 0,                   // 有效期类型：0-天数，1-时间范围
          validDay: 0,                    // 有效天数
          state: 1,                       // 状态：0-关闭，1-开启，-1删除
          validStartTime: undefined,      // 使用有效期 开始时间
          validEndTime: undefined,        // 使用有效期 结束时间
          receiveStartTime: undefined,    // 可领取 开始时间
          receiveEndTime: undefined,      // 可领取 结束时间
          total:undefined,                // 总数量
          isLimited:1,                    // 是否限量： 0-不限量， 1-限量
          useScope:0,                     // 使用范围：0-不限，1-指定商品
          useGoodsId:undefined,              // 商品id
        },
        couponTemplateId:undefined,               // 优惠券id
        isValidDate:'',                   // 使用有效期范围
        isReceiveDate:'',                 // 领取时间
        useGoodsList:[],
        rules: {
          couponTemplateName: [{
            required: true,
            message: '请输入优惠券名称',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '请选择优惠券类型',
            trigger: 'change'
          }],
          useScope: [{
            required: true,
            message: '请选择优惠券适用范围',
            trigger: 'change'
          }],
          validType:[{
            required: true,
            message: '请选择有效期类型',
            trigger: 'change',
          }],
          isLimited:[{
            required: true,
            message: '请选择是否限量',
            trigger: 'change'
          }],
          state: [{
            required: true,
            message: '请选择优惠券状态',
            trigger: 'change'
          }],
        },
        typeOptions: [{
          "label": "满减券",
          "value": 0
        },{
          "label": "折扣券",
          "value": 1
        }],
        useOptions: [{
          "label": "不限",
          "value": 0
        },{
          "label": "指定商品",
          "value": 1
        }],
        validTypeOptions: [{
          "label": "天数",
          "value": 0
        }, {
          "label": "时间范围",
          "value": 1
        }],
        stateOptions: [{
          "label": "开启",
          "value": 1
        }, {
          "label": "关闭",
          "value": 0
        }, {
          "label": "删除",
          "value": -1
        }],
        isLimitedOptions: [{
          "label": "限量",
          "value": 1
        }, {
          "label": "不限量",
          "value": 0
        }],
      }

    },
    computed:{
      title() {
        return this.couponTemplateId ? '编辑优惠券' : '添加优惠券'
      },
    },
    mounted() {
      this.loadUseGoodsList();
    },
    methods: {

      //加载 适用优惠券适用范围的 商品列表
      async loadUseGoodsList(){
        let res = await getUseGoodsList();
        this.useGoodsList = res.data;
      },

      //
      async open(couponTemplateId) {
        this.resetForm();
        this.loading = false;
        this.dialog = true;
        if(couponTemplateId){
          this.couponTemplateId = couponTemplateId;
          // 获取优惠券详情
          var res = await infoCoupon(couponTemplateId);
          var data = res.data;
          for (let key in this.formData) {
            if (data.hasOwnProperty(key)) {
              this.formData[key] = data[key];
            }
          }
          // 设置是否限量
          this.formData.isLimited = res.data.isLimited?1:0
          // 设置区间值
          this.isValidDate = [this.formData.validStartTime==null?'':this.formData.validStartTime,this.formData.validEndTime==null?'':this.formData.validEndTime];
          this.isReceiveDate = [this.formData.receiveStartTime==null?'':this.formData.receiveStartTime,this.formData.receiveEndTime==null?'':this.formData.receiveEndTime];
        }
      },

      // 选择优惠券类型
      typeChange(value){
        if(value==0){
          this.formData.discount = undefined;
        }else{
          this.formData.minPrice = undefined;
          this.formData.couponPrice = undefined;
        }
      },

      // 优惠券适用范围
      useChange(value){
        if(value==0){
          this.formData.useGoodsId = undefined;
        }
      },

      // 点击 有效期类型
      validTypeChange(value){
        if(value==1){
          this.formData.validStartTime = undefined;
          this.formData.validEndTime = undefined;
        }else{
          this.formData.validDay = 0;
        }
      },

      // 选择 使用有效期
      selectValidDate(isValidDate){
        if(isValidDate != null && isValidDate.length == 2) {
          this.formData.validStartTime = isValidDate[0];
          this.formData.validEndTime = isValidDate[1];
        }
      },

      // 选择 领取有效期
      selectReceiveDate(isReceiveDate){
        if(isReceiveDate != null && isReceiveDate.length == 2) {
          this.formData.receiveStartTime = isReceiveDate[0];
          this.formData.receiveEndTime = isReceiveDate[1];
        }
      },

      // 点击 是否限量
      isLimitedChange(value){
        this.formData.total = value==0?0:this.formData.total;
      },

      // 创建 提交
      submitForm(){
        this.$refs['elForm'].validate(async valid => {
          if (!valid) return
          if(this.formData.type==0&&this.formData.minPrice==0){
            this.$message.error('请输入最低消费金额');
            return false;
          }else if(this.formData.type==0&&this.formData.couponPrice==0){
            this.$message.error('请输入优惠金额');
            return false;
          }else if(this.formData.useScope==1&&this.formData.useGoodsId==undefined){
            this.$message.error('请选择商品');
            return false;
          }else if(this.formData.type==1&&!this.formData.discount){
            this.$message.error('请输入折扣');
            return false;
          }else if(this.formData.validType==1&&this.isValidDate==''){
            this.$message.error('请选择使用有效期限');
            return false;
          }else if(this.formData.validType==0&&this.formData.validDay==0){
            this.$message.error('请输入使用有效天数');
            return false;
          }else if(this.formData.isLimited==1&&this.formData.total==0){
            this.$message.error('请输入优惠券发布数量');
            return false;
          }else if(!this.formData.receiveStartTime||!this.formData.receiveEndTime){
            this.$message.error('请选择领取时间范围');
            return false;
          }
          if(this.formData.isLimited==0){
            this.formData.total = 0;
          }
          if(!this.formData.validStartTime){
            this.formData.validStartTime = undefined;
          }
          if(!this.formData.validEndTime){
            this.formData.validEndTime = undefined;
          }
          if(this.formData.discount==0||this.formData.discount==''){
            this.formData.discount = undefined;
          }
          this.loading = true;
          try {
            if(!this.couponTemplateId){
              var data = Object.assign({}, this.formData);
              var res = await addCoupon(data);
              this.$utils.showSuccessMessage(res.msg, () => {
                this.close();
                this.$parent.searchTable();
              });
            }else{
              var data = Object.assign({couponTemplateId:this.couponTemplateId}, this.formData);
              var res = await updateCoupon(data);
              this.$utils.showSuccessMessage(res.msg, () => {
                this.close();
                this.$parent.searchTable();
              });
            }

          } finally {
            this.loading = false;
          }
        })
      },

      close() {
        this.loading = false;
        this.dialog = false;
        this.resetForm();
      },

      resetForm() {
        if (this.$refs.elForm !== undefined) {
          this.$refs.elForm.resetFields();
        }
        this.isValidDate = '';
        this.isReceiveDate = '';
        this.formData.useGoodsId = undefined;
        this.couponTemplateId=undefined;
        this.formData.validStartTime = undefined;        // 使用有效期 开始时间
        this.formData.validEndTime = undefined;          // 使用有效期 结束时间
        this.formData.receiveStartTime = undefined;      // 可领取 开始时间
        this.formData.receiveEndTime = undefined;        // 可领取 结束时间
      },
    }
  }
</script>

<style scoped lang="scss">
    ::v-deep .disabled .el-upload--picture-card {
      display: none;
    }
    ::v-deep .el-dialog__body{height: 78vh;overflow: auto;}
</style>
